const map = (fn, array) => {
  let result = []
  for(const val of array) {
    result.push(fn(val))
  }
  return result
}

const filter = (fn, array) => {
  let result = []
  for(const val of array) {
    fn(val) && result.push(val)
  }
  return result
}

//把嵌套数据连接到一个数组
const concatAll = array => {
  let results = []
  for(const val of array) {
    results.push.apply(results, val)
  }
  return results
}

const reduce = (fn, init, array) => {
  let acc
  if(init === undefined) {
    acc = array[0]
    for(let i = 1; i < array.length; i++) {
      acc = fn(acc, array[i])
    }
  } else {
    acc = init
    for(const val of array) {
      acc = fn(acc, val)
    }
  }
  return acc
}

const zip = (fn, left, right) => {
  let results = []
  for(let i = 0; i < Math.min(left.length, right.length); i++) {
    results.push(fn(left[i], right[i]))
  }
  return results
}

module.exports = {
  map, filter, concatAll, reduce, zip
}
